package cn.turboinfo.fuyang.api.domain.admin.usecase.company;

import cn.turboinfo.fuyang.api.domain.common.service.company.HousekeepingCompanyService;
import cn.turboinfo.fuyang.api.domain.common.service.user.UserCredentialService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.company.HousekeepingCompany;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.UserCredential;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;

/**
 * 查看 appSecret
 *
 * @author hai
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class HousekeepingCompanyViewAppSecretUseCase extends AbstractUseCase<HousekeepingCompanyViewAppSecretUseCase.InputData, HousekeepingCompanyViewAppSecretUseCase.OutputData> {
    private final HousekeepingCompanyService housekeepingCompanyService;

    private final UserCredentialService userCredentialService;

    @Override
    protected OutputData doAction(InputData inputData) {

        // 验证密码
        // 解密前端加密内容
        String credential = userCredentialService.decrypt(inputData.getPassword());

        // 凭据ID
        UserCredential userDefault = userCredentialService.findUserDefault(inputData.getUserId()).orElseThrow();

        // 验证凭据
        if (!userCredentialService.match(userDefault.getId(), credential)) {
            throw new RuntimeException("密码不正确");
        }

        HousekeepingCompany housekeepingCompany = housekeepingCompanyService.getByIdEnsure(inputData.getCompanyId());

        return OutputData.builder()
                .appSecret(housekeepingCompany.getAppSecret())
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        @NotNull(
                message = "userId不能为空"
        )
        private Long userId;

        @NotNull(
                message = "companyId不能为空"
        )
        private Long companyId;

        @NotNull(
                message = "password不能为空"
        )
        private String password;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private String appSecret;
    }

}
